﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace GiteePlugin.Core.Auth
{
    /// <summary>
    /// Gitee 认证令牌缓存容器
    /// 说明：采用单例模式存储令牌信息
    /// </summary>
    public class AuthTokenCache
    {
        /// <summary>
        /// 访问令牌（Access Token）
        /// 有效期通常为2小时
        /// </summary>
        public string? AccessToken { get; internal set; }

        /// <summary>
        /// 刷新令牌（Refresh Token）
        /// 有效期通常为30天
        /// </summary>
        public string? RefreshToken { get; internal set; }

        /// <summary>
        /// 令牌过期时间（UTC时间）
        /// 包含提前5分钟的安全缓冲期
        /// </summary>
        public DateTime ExpireTimeUtc { get; internal set; }

        /// <summary>
        /// 令牌是否即将过期
        /// 检查条件：当前时间 >= (过期时间 - 5分钟)
        /// </summary>
        public bool IsNearExpiration =>
            DateTime.UtcNow >= ExpireTimeUtc.AddMinutes(-5);

        /// <summary>
        /// 更新令牌缓存
        /// </summary>
        /// <param name="response">令牌响应</param>
        public void Update(AuthTokenResponse response)
        {
            AccessToken = response.AccessToken;
            RefreshToken = response.RefreshToken;
            ExpireTimeUtc = DateTime.UtcNow.AddSeconds(response.ExpiresIn);
        }

        /// <summary>
        /// 清空令牌缓存
        /// </summary>
        public void Clear()
        {
            AccessToken = null;
            RefreshToken = null;
            ExpireTimeUtc = DateTime.MinValue;
        }
    }

    /// <summary>
    /// 令牌响应模型（与Gitee API响应格式匹配）
    /// </summary>
    public class AuthTokenResponse
    {
        [JsonPropertyName("access_token")]
        public string AccessToken { get; set; } = string.Empty;

        [JsonPropertyName("refresh_token")]
        public string RefreshToken { get; set; } = string.Empty;

        [JsonPropertyName("expires_in")]
        public int ExpiresIn { get; set; }

        [JsonPropertyName("token_type")]
        public string TokenType { get; set; } = "Bearer";
    }
}
